<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Oauth登录</title>
  <script src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script type="text/javascript" src="https://cdn.bootcdn.net/ajax/libs/vConsole/3.3.4/vconsole.min.js"></script>

  <script type="text/javascript">

    //接口地址
    let baseUrl = "http://192.168.0.1:9999/wechat/cgi-bin";
    //政务微信corpid
    let corpid = '***';

    //应用secret
    let corpsecret = '***';

    //应用id
    let agentid = ***;

    //oauth2登录地址
    let oauth2Url = 'http://124.234.165.48:90';

    //console控制台
    let vConsole = new VConsole();

    /**
     * oauth2登录
     * 1、判断用户是否已登录（cookie或sessionStorage判断登录标识，本示例省略此步骤）
     * 2、判断浏览器地址栏上是否有code
     * 3、没有code重定向到oauth2登录地址
     * 4、如果有code 则使用code获取登录用户id
     * 5、
     */
    function login() {
      let params = new URLSearchParams(location.search);
      if (params.has('code')) {
        let code = params.get('code');
        //code换用户信息
        getUserInfoByCode(code);
      } else {
        //oauth2重定向地址  参考政务微信api文档
        let redirectUri = location.href.split("#")[0];
        let url = 'oauth2Url/connect/oauth2/authorize?appid=CORPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&agentid=AGENTID&state=STATE#wechat_redirect';
        url = url.replace('CORPID', corpid).replace('REDIRECT_URI', redirectUri).replace('AGENTID', agentid).replace('oauth2Url',oauth2Url);
        location.href = url;
      }
    }

    async function getUserInfoByCode(code) {

      let accessTokenResp = await getAccessToken();
      if (accessTokenResp.data.errcode == 0) {
        //获取用户id、用户类型
        let url = baseUrl + '/user/getuserinfo';
        let resp = await axios.get(url, {
          params: {
            'access_token': accessTokenResp.data.access_token, 'code': code
          }
        });
        if (resp.data.errcode == 0) {
          alert(`获取用户id：${resp.data.UserId}`);
        }
        console.log(resp.data);

      } else {
        alert('获取accessToken失败');
      }
    }
    //根据corpid和应用secret获取accessToken，需要缓存7000秒
    function getAccessToken() {
      return axios.get(baseUrl + '/gettoken', {
        params: {
          'corpid': corpid, 'corpsecret': corpsecret
        }
      });
    }
    //默认调用登录方法
    login();

  </script>
</head>
<body>

</body>
</html>
